package com.example.retailmanagement.controller;

import com.example.retailmanagement.model.Order;
import com.example.retailmanagement.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/orders")
public class OrderController {

    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderService orderService;

    // 插入订单
    @PostMapping
    public ResponseEntity<Boolean> insertOrder(@RequestBody Order order) {
        logger.info("开始插入订单，订单信息：{}", order);
        boolean result = orderService.insertOrder(order);
        if (result) {
            logger.info("订单插入成功");
            return new ResponseEntity<>(true, HttpStatus.OK);
        } else {
            logger.error("订单插入失败");
            return new ResponseEntity<>(false, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 更新订单
    @PutMapping("/{id}")
    public ResponseEntity<Boolean> updateOrder(@PathVariable Long id, @RequestBody Order order) {
        order.setId(id);
        logger.info("开始更新订单ID为 {} 的订单，更新信息：{}", id, order);
        boolean result = orderService.updateOrder(order);
        if (result) {
            logger.info("订单更新成功，订单ID：{}", id);
            return new ResponseEntity<>(true, HttpStatus.OK);
        } else {
            logger.error("订单更新失败，订单ID：{}", id);
            return new ResponseEntity<>(false, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 获取所有订单
    @GetMapping
    public ResponseEntity<List<Order>> getAllOrders() {
        logger.info("开始获取所有订单");
        List<Order> orders = orderService.getAllOrders();
        logger.info("成功获取到 {} 个订单", orders.size());
        return new ResponseEntity<>(orders, HttpStatus.OK);
    }

    // 获取指定订单
    @GetMapping("/{id}")
    public ResponseEntity<Order> getOrderById(@PathVariable Long id) {
        logger.info("开始获取ID为 {} 的订单", id);
        Order order = orderService.getOrderById(id);
        if (order!= null) {
            logger.info("成功获取到订单ID为 {} 的订单信息：{}", id, order);
            return new ResponseEntity<>(order, HttpStatus.OK);
        } else {
            logger.warn("未找到ID为 {} 的订单", id);
            return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
        }
    }
}